import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:chop/Model/order_entity.dart';
import 'package:chop/Model/order_img_entity.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/common/configs.dart';
import 'package:chop/view/Driver/riderOrderItem.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/behavior.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:loading_animations/loading_animations.dart';
import 'dart:ui' as ui;
import 'package:chop/view/home/place_an_order/Delivery_order.dart';

//正在进行订单
class MyOrderInfo extends StatefulWidget {
  final String uuid;

  const MyOrderInfo({Key key, this.uuid}) : super(key: key);

  @override
  _OrdedrInfoState createState() => _OrdedrInfoState();
}

class _OrdedrInfoState extends State<MyOrderInfo> {
  // 是否在网络请求中
  bool isNetworkNotBad = false;
  var _imgPath;

  // 订单id
  String uuid;

  // 当前位置
  Position nowPosition;

  // 订单信息
  orderData data;
  List<OrderInfo> infos = [];
  List<OrderImg> imgs = [];

  // 地图标记
  Set<Marker> Markers = Set();

  // 地图控制器
  Completer<GoogleMapController> _controller = Completer();

  Widget getBody() {
    if (isNetworkNotBad) {
      print("加载完成");
      if(infos.length == 3){
        return getInfo(data);
      }else{
        return _buildBody();
      }
    } else {
      print("正在加载");
      return Center(child: LoadingJumpingLine.square());
    }
  }

  Widget _buildBody() {
    return Container(
      child: Stack(
        children: <Widget>[
          GoogleMap(
            initialCameraPosition: CameraPosition(
              target: LatLng(
                  double.parse(data.beginLat), double.parse(data.beginLng)),
              zoom: 14.4746,
            ),
            markers: Markers,
            onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
            },
          ),
          Positioned(
              bottom: 10,
              height: 300,
              width: MediaQuery.of(context).size.width,
              child: ScrollConfiguration(
                behavior: MyBehavior(),
                child: ListView(
                  children: <Widget>[
                    Container(
                      height: 10,
                    ),
                    getColumn("订单信息",
                        child: Column(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Column(
                                      children: <Widget>[
                                        Row(
                                          children: <Widget>[
                                            Container(
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单号：${data.uuid}",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                    fontSize: 16,
                                                    fontWeight:
                                                    FontWeight.bold),
                                              ),
                                            )
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Container(
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单状态：${getStatus(data.status)} (${ getS(infos.length)})",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                  fontSize: 16,
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_right,
                                                size: 15,
                                                color: Colors.greenAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.begin}",
                                                  textAlign: TextAlign.left,
                                                  maxLines: 4,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_left,
                                                size: 15,
                                                color: Colors.redAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.end}",
                                                  textAlign: TextAlign.left,
                                                  overflow:
                                                  TextOverflow.ellipsis,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: FixedSizeText(
                                                  "路程",
                                                  style: TextStyle(
                                                      color: Colors.black45),
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                alignment: Alignment.topRight,
                                                child: FixedSizeText(
                                                    "${data.distance} km   "),
                                              ),
                                            )
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: FixedSizeText(
                                                  "跑腿费",
                                                  style: TextStyle(
                                                      color: Colors.black45),
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                alignment: Alignment.topRight,
                                                child: FixedSizeText(
                                                    "${StringUtils.formatNum(data.money * 0.8, 2)} \$   "),
                                              ),
                                            )
                                          ],
                                        ),
                                      ],
                                    ),
                                    flex: 8,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        )),
                    infos.length != 0
                        ? getColumn("运送信息",
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    child: FixedSizeText(
                                      "骑手",
                                      style: TextStyle(
                                          color: Colors.black45),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.topRight,
                                    child: FixedSizeText(
                                        "${data.riderName}"),
                                  ),
                                )
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    child: FixedSizeText(
                                      "接单时间",
                                      style: TextStyle(
                                          color: Colors.black45),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.topRight,
                                    child: FixedSizeText(
                                        "${infos[0].createTime}"),
                                  ),
                                )
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    child: FixedSizeText(
                                      "预计送达时间",
                                      style: TextStyle(
                                          color: Colors.black45),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.topRight,
                                    child: FixedSizeText(
                                        "${data.estimatedTime??''}"),
                                  ),
                                )
                              ],
                            ),
                            infos.length>=2?MyImageView(context,0,imgPath: _imgPath,imgs: imgs):Container(),
                            infos.length>=2? Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    child: FixedSizeText(
                                      "取件时间",
                                      style: TextStyle(
                                          color: Colors.black45),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.topRight,
                                    child: FixedSizeText(
                                        "${infos[1].createTime}"),
                                  ),
                                )
                              ],
                            ):Container(),
                            infos.length>=3? Row(
                              children: <Widget>[
                                Expanded(
                                  child: Container(
                                    child: FixedSizeText(
                                      "送达时间",
                                      style: TextStyle(
                                          color: Colors.black45),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    alignment: Alignment.topRight,
                                    child: FixedSizeText(
                                        "${infos[2].createTime}"),
                                  ),
                                )
                              ],
                            ):Container(),
                            infos.length>=2? MyImageView(context,1,imgPath: _imgPath,imgs: imgs):Container(),
                          ],
                        ))
                        : Container(),
                    getColumn(
                      "备注信息",
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: FixedSizeText(data.remark ?? ""),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }

  String getS(int len) {
    switch (len) {
      case 0:
        return "正在等待接单";
      case 1:
        return "骑手正在赶往取货点";
      case 2:
        return "骑手正在送货";
      case 3:
        return "订单已完成";
    }
  }

  String getStatus(String status) {
    switch (status) {
      case "0":
        return "进行中";
      case "1":
        return "已完成";
      case "2":
        return "未付款";
      case "3":
        return "待接单";
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BaseViewBar(
        childView: BaseTitleBar("订单详情"),
        preferredSize: Size.fromHeight(50.0),
      ),
      body: getBody(),
    );
  }

  @override
  void initState() {
    this.uuid = widget.uuid;
    // TODO: implement initState
    super.initState();
    getData();
  }

  Future<void> getData() async {
    await DioUtils.orderInfo(uuid).then((Map result) async {
      if (result['code'] == 0) {
        data = orderData.fromJson(result['data']);
        if (data.status == "0") {
          await DioUtils.orderInfoList(data.uuid).then((val) {
            if (val.code == 0) {
              json.decode(val.data)['infos'].forEach((v) {
                infos.add(OrderInfo.fromJson(v));
              });
              json.decode(val.data)['imgs'].forEach((v) {
                imgs.add(OrderImg.fromJson(v));
              });
            } else {
              print("获取进行中订单出错:${val.msg}");
            }
            buildLine();
            setState(() {
              isNetworkNotBad = true;
            });
          });
        } else {
          buildLine();
          setState(() {
            isNetworkNotBad = true;
          });
        }

        //图标
//        final Uint8List markerIcon =
//            await getBytesFromAsset('asset/map/begin.png', 150);
//        final Uint8List endIcon =
//            await getBytesFromAsset('asset/map/end.png', 150);
        // 标记起送地点

      }
    });
  }

  // 构建路线导航
  void buildLine() async {
    // 获取当前坐标
    nowPosition = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    Markers.add(Marker(
        markerId: MarkerId("begin"),
        infoWindow: InfoWindow(
          title: "起送地点",
        ),
//            icon: BitmapDescriptor.fromBytes(markerIcon),
        position:
        LatLng(double.parse(data.beginLat), double.parse(data.beginLng))));
//    Markers.add(Marker(
//        markerId: MarkerId("my"),
//        infoWindow: InfoWindow(
//          title: "我的位置",
//        ),
////            icon: BitmapDescriptor.fromBytes(endIcon),
//        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
//        position: LatLng(nowPosition.latitude, nowPosition.longitude)));
    // 标记送达地点
    Markers.add(Marker(
        markerId: MarkerId("end"),
        infoWindow: InfoWindow(
          title: "送达地点",
        ),
//            icon: BitmapDescriptor.fromBytes(endIcon),
        position:
        LatLng(double.parse(data.endLat), double.parse(data.endLng))));
  }





// 获取图标 base64
  Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    ui.FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ui.ImageByteFormat.png))
        .buffer
        .asUint8List();
  }
}

/*图片控件*/
Widget MyImageView(context,int imgType,{imgs,imgPath}) {
  String str = "";
  Widget img;
  switch (imgType) {
    case 0:
      str += "货物运送拍照：  ";
      if(imgs.length == 0){
        if(imgPath != null){
          str += "已拍照";
          img = Container(
            child: GestureDetector(
              child: FixedSizeText("点击查看"),
              onTap: (){
                Get.defaultDialog(
                    title: "查看图片",
                    content:Container(
                      child: Image.file(imgPath),
                    ) );
              },
            ),
          );
//            img = Image.file(_imgPath);
        }else{
          str += "未拍照";
          img = Container();
        }
      }else{
        print(imgs.isEmpty);
        if(imgs.length != 0){
          var fl = true;
          imgs.forEach((val){
            print("____________${val.imgType}");
            if(val.imgType == "0"){
              str += "已拍照";
              img = Container(
                child: GestureDetector(
                  child: FixedSizeText("点击查看"),
                  onTap: (){
                    Get.defaultDialog(
                        title: "查看图片",
                        content:Container(
                          child: Image.network(Configs.URL+val.address),
                        ) );
                  },
                ),
              );
              fl = false;
            }
          });
          if(fl){
            str = "未拍照";
            img = Container();
          }
        }
      }
      break;
    case 1:
      str += "送达拍照：  ";
      if(imgs.length == 1){
        if(imgPath != null){
          str += "已拍照";
          img = Container(
            child: GestureDetector(
              child: FixedSizeText("点击查看"),
              onTap: (){
                Get.defaultDialog(
                    title: "查看图片",
                    content:Container(
                        child: Image.file(imgPath)
                    ) );
              },
            ),
          );
        }else{
          str += "未拍照";
          img = Container();
        }
      }else{
        print(imgs.isEmpty);
        if(imgs.length != 1){
          var fl = true;
          imgs.forEach((val){
            print("____________${val.imgType}");
            if(val.imgType == "1"){
              str = "已拍照";
              img = Container(
                child: GestureDetector(
                  child: FixedSizeText("点击查看"),
                  onTap: (){
                    Get.defaultDialog(
                        title: "查看图片",
                        content:Container(
                          child: Image.network(Configs.URL+val.address),
                        ) );
                  },
                ),
              );
              fl = false;
            }
          });
          if(fl){
            str = "未拍照";
            img = Container();
          }
        }
      }
      break;
    case 2:
      break;
    case 3:
      break;
  }
  return Row(
    children: <Widget>[
      Container(
        child: FixedSizeText(
          str,
          style: TextStyle(color: Colors.black45),
        ),
      ),
      Expanded(
          child: Container(
              alignment: Alignment.topRight,
              child:img
          ))
    ],
  );

}